//
//  StatisticsServer.cpp
//  Simulation
//
//  Created by Christopher Kemsley on 3/7/12.
//  Copyright (c) 2012 iAppolopolis. All rights reserved.
//

#include "Statistics.hpp"
#include "System.hpp"
#include <iostream>



SimNamespaceBegin

std::ostream&	operator<<	( std::ostream & stream , StateStat const & node )
	{
	StateStat::Map::const_iterator	here	=	node.mPeriods.begin() ;
	StateStat::Map::const_iterator	end		=	node.mPeriods.end() ;
	while ( here != end )
		{
		stream << StateStatServer :: rowPrefix << "	" << node.mName << "	" << (here->first) << "	" << (here->second) << "\n" ;
		here ++ ;
		}
	
	return stream ;
	}




std::string	StateStatServer :: rowPrefix ;







StateStat :: StateStat	( std::string const & name , char const * defaultState )
:	mName	( name )
,	mState	( defaultState )
,	mSlot	( System::shared().currentSlot() )
,	mPeriods()
	{
	
	}
StateStat :: ~StateStat	()
	{
	(*this) << "Idle" ;
	std::cout << (*this) ;
	}

void	StateStat :: operator<<	( char const * state )
	{
	if ( state == mState ) return ;
	
	UInteger	now		=	System::shared().currentSlot() ;
	UInteger	diff	=	now - mSlot ;
	
	_add ( mState , diff ) ;
	
	mSlot				=	now ;
	mState				=	state ;
	}
void	StateStat :: operator<=	( char const * state )
	{
	if ( state == mState ) return ;
	
	UInteger	now		=	System::shared().currentSlot() ;
	UInteger	diff	=	now - mSlot ;
	
	_add ( state , diff ) ;
	
	mSlot				=	now ;
	mState				=	state ;
	}




void	StateStat :: _add ( char const * state , UInteger value )
	{
	Map::iterator found = mPeriods . find ( state ) ;
	if ( found == mPeriods.end() )
		mPeriods[state] = value ;
	else
		(found->second) += value ;
	}



SimNamespaceEnd
